//persistent.js
//The goal is to allow persistent storage of the Knowledge Base,
//but for the moment we only want to show social data in relfinder.dbpedia.org via Jena

var updateServer = "http://localhost:2020/update/service";
var lastUpdateIndex = 0;
var updateTimeInterval = 3;
var tripleNumberLimit = 5000; //some error about "Form too large" would
                              //showup if this is not set
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cr = Components.results;
var idleService = Cc["@mozilla.org/widget/idleservice;1"].
    getService(Ci.nsIIdleService);


function PersistentStoreMaintainer(kb){
  this.kb = kb;
  var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  var _this = this;
  this.psmIdleObserver = {
  observe: function psmIdleObserve(aSubject, aTopic, aData) {
      _this.sendKbToBackendServer(); 
    } 
  }
  idleService.addIdleObserver(this.psmIdleObserver, updateTimeInterval);

  dump("update idle observer is set!\n");
} 
PersistentStoreMaintainer.prototype.sendKbToBackendServer = 
function sendKbToBackendServer(){
  var xhr = Util.XMLHTTPFactory();
  xhr.open('POST', updateServer, true);
  xhr.setRequestHeader('Content-Type', 
                       'application/x-www-form-urlencoded');
  var stsToSend = this.kb.statements.slice(lastUpdateIndex);
  if (!stsToSend.length) return; //nothing new, don't update
  dump("sending data to backend server " + updateServer + 
       " lastUpdateIndex=" + lastUpdateIndex + "...\n");
  if (stsToSend.length > tripleNumberLimit){
    dump(stsToSend.length + " > " + tripleNumberLimit);
    stsToSend.splice(tripleNumberLimit);
    lastUpdateIndex = lastUpdateIndex + tripleNumberLimit;
  } else {    
    lastUpdateIndex = lastUpdateIndex + stsToSend.length;
  }
  var updateQuery = "INSERT {" + 
                    stsToSend.map(function(x) x.toString()).join("") + "}";
  var psmIdleObserver = this.psmIdleObserver;
  xhr.onreadystatechange = function(){
    if (xhr.readyState == 4 && xhr.status == 0){
      dump("SPARQL Update server is not set up.\n");
      idleService.removeIdleObserver(psmIdleObserver, 
                                     updateTimeInterval);
    }      
  }
  xhr.send("request=" + encodeURIComponent(updateQuery).
           replace(/%20/g, '+'));
};
